package com.qingzhu.controller.shopserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.Address;
import com.qingzhu.pojo.ShopCart;
import com.qingzhu.pojo.ShopOption;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.AddressService;
import com.qingzhu.service.ShopOptionService;
import com.qingzhu.service.impl.AddressServiceImpl;
import com.qingzhu.service.impl.ShopOptionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/cart/add")
public class AddCartController extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    ShopOptionService shopOptionService = new ShopOptionServiceImpl();
    AddressService addressService = new AddressServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("添加购物选项服务..");
        String shopNum = req.getParameter("shopNum");
        String itemId = req.getParameter("itemId");
        String provinceId = req.getParameter("provinceId");
        String cityId = req.getParameter("cityId");
        String areaId = req.getParameter("areaId");
        System.out.println("将要添加的商品id："+itemId+" 购买数量："+shopNum);

        // 获取token信息（最新方案）
        String token = req.getHeader("token");
        token = URLDecoder.decode(token,"UTF-8");   // 解码
        token = token.substring(1,token.length()-1);    // 去除字符串前后位置上的引号(提取购物车信息)

        // 获取cookie信息（弃用方案）
        Cookie[] cookies = req.getCookies();

        // 如果前台没有验证信息传过来，就创建一个购物车，否则就执行添加
        if (token.equals("null")){
            // 创建一个购物车
            ShopCart shopCart = createdShopCart(Integer.parseInt(shopNum), Integer.parseInt(itemId), provinceId, cityId, areaId);
            // 创建cookie（兼容cookie技术）
            createdCookie(resp,shopCart);
            resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,"OK",shopCart)));
        }else {
            Boolean isCookie = false;   // 是否使用cookie中的购物车
            // 将购物车反序列化
            ShopCart shopCart = objectMapper.readValue(token, ShopCart.class);
            // 处理cookie（兼容cookie技术）
            if (cookies != null && cookies[0].getValue() != "") {
                String cartJson = cookies[0].getValue();
                // 解析购物车信息
                String decode = URLDecoder.decode(cartJson, "UTF-8");
                // 通过反序列获取到购物车
                shopCart = objectMapper.readValue(decode, ShopCart.class);
//            List<ShopOption> shopCart = objectMapper.readValue(decode, new TypeReference<List<ShopOption>>(){});
//            List<ShopOption> shopCart = JSONArray.parseArray(decode, ShopOption.class);
                System.out.println("检测到cookie中存在购物车："+shopCart);
                // 声明可以使用cookie技术
                isCookie = true;
            } else {
                System.out.println("检测到浏览器对cookie的支持可能不稳定...将自动切换到token技术");
            }
            // 处理购物车选项列表
            shopCart = shopOptionService.addShopSption(shopCart, Integer.parseInt(shopNum), Integer.parseInt(itemId));
            // 处理cookie（兼容cookie技术）
            if (isCookie) {
                // 创建cookie
                createdCookie(resp,shopCart);
            }
            System.out.println("添加预览："+shopCart);
            resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,"OK",shopCart)));
        }
    }


    // 创建一个购物车
    public ShopCart createdShopCart(Integer shopNum,Integer itemId,String provinceId,String cityId,String areaId) throws IOException {
        // 创建购物车选项列表
        ShopOption shopOption = shopOptionService.createdOption(shopNum, itemId);
        List<ShopOption> shopOptions = new ArrayList<>();
        shopOptions.add(shopOption);
        // 封装购物选项列表和收货地址到购物车中
        ShopCart shopCart = new ShopCart();
        shopCart.setShopOptions(shopOptions);
        Address receivingAddress = addressService.findReceivingAddress(provinceId, cityId, areaId);
        shopCart.setReceivingAddress(receivingAddress);
        return shopCart;
    }
    // 创建一个cookie
    public void createdCookie(HttpServletResponse resp,ShopCart shopCart) throws IOException {
        // 将购物车序列化成json串
        String cartJson = objectMapper.writeValueAsString(shopCart);
        // 将购物车的信息编码后再储存，否则可能会抛出不合法的字符异常
        String encodeCart = URLEncoder.encode(cartJson, "UTF-8");
        Cookie cookie = new Cookie("cart", encodeCart);
        resp.addCookie(cookie);
    }
}
